/**
 * @author spider
 * Implementation of socket for the manager (see Socket on core.message)
 */
package br.unb.core.manager;

import br.unb.core.dispatcher.DispatcherSocket;
import br.unb.core.message.Message;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;


import br.unb.utils.Console;
import br.unb.utils.Resource;

public class ManagerSocket extends br.unb.core.message.Socket {

    private static final ManagerSocket INSTANCE = new ManagerSocket();//no lazy initialization

    public static ManagerSocket getInstance() {
        return INSTANCE;
    }

    private ManagerSocket() {
        try {
            super.setName("9999");
            socket = new DatagramSocket(CONTROL_PORT);
            socket.setSoTimeout(10000);
        } catch (SocketException e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    public Message sendControlMessage(Message message, InetAddress dst, int nrTry) {
        int count = 0;
        while (count < nrTry) {
            super.send(message, dst, DISPATCHER_PORT);
            Message m = super.receive();
            if (Message.verifyError(m)) {
                count++;
                Console.println(
                        "Message " + Integer.toString(count)
                        + ": \n" + (m != null ? m.toString() : ""), System.err, doc);
            } else {
                return m;
            }
        }
        Message msg = new Message(Message.Type.ERROR,
                Resource.getString("ERROR_SENDING_CONTROL_MESSAGE_REPONSE_TIMEOUT_EXCEEDED")
                + message.getText());
        printError(
                "\n" + Resource.getString("SEND_TO______:")// 14 chars wide
                + dst.getHostAddress() + ","
                + Integer.toString(DispatcherSocket.DISPATCHER_PORT), msg);
        return msg;
    }
}
